﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace OS.Common.Extention
{
    /// <summary>
    /// XML转换扩展方法类
    /// </summary>
    public static class XmlConvertExtention
    {
        /// <summary>
        /// 对象序列化成xml字符串
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string SerializeToXml(this object t)
        {
            MemoryStream memoryStream = null;
            StreamReader streamReader = null;
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(t.GetType());
                memoryStream = new MemoryStream();
                xmlSerializer.Serialize(memoryStream, t);
                memoryStream.Position = 0L;
                streamReader = new StreamReader(memoryStream);
                return streamReader.ReadToEnd();
            }
            finally
            {
                streamReader?.Dispose();
                memoryStream?.Dispose();
            }
        }

        /// <summary>
        /// xml字符串转化到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeserializeXml<T>(this string xml) where T : class
        {
            return (T)(xml.DeserializeXml(typeof(T)) as T);
        }

        /// <summary>
        /// xml字符串转化到对象
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object DeserializeXml(this string xml, Type type)
        {
            MemoryStream memoryStream = null;
            StreamWriter streamWriter = null;
            try
            {
                memoryStream = new MemoryStream();
                streamWriter = new StreamWriter(memoryStream);
                streamWriter.Write(xml);
                streamWriter.Flush();
                memoryStream.Position = 0L;
                return new XmlSerializer(type).Deserialize(memoryStream);
            }
            finally
            {
                streamWriter?.Dispose();
                memoryStream?.Dispose();
            }
        }
    }
}